﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using AccountProxy = ChatForum.Client.AccountServiceProxy;
using ForumProxy = ChatForum.Client.ForumServiceProxy;

namespace ChatForum.Client
{
	public partial class PostThread : BasePage
	{
		private Guid RootPostId
		{
			get
			{
				Guid outId;
				return Guid.TryParse(Request.QueryString["postId"], out outId) ? outId : Guid.Empty;
			}
		}
		private ForumProxy.Post RootPost
		{
			get { return ServiceHelper.Instance.ForumService.GetPostById(RootPostId); }
		}
		public bool ReplyButtonVisibility { get { return User.Identity.IsAuthenticated; } }

		protected void Page_PreInit(object sender, EventArgs e)
		{
			if (User.Identity.IsAuthenticated)
			{
				this.MasterPageFile = "~/MemberLayout.master";
			}
		}
		protected void Page_Load(object sender, EventArgs e)
		{
			if (!IsPostBack)
			{
				LoadPostList();
			}
		}

		private void LoadPostList()
		{
			categoryLabel.Text = (new MyPostView(RootPost)).CategoryName;

			postListView.DataSource = ServiceHelper.Instance.ForumService.GetThread(RootPostId).Select(p => new MyPostView(p));
			postListView.DataBind();
		}
		protected void OnReplyPost(object sender, EventArgs e)
		{
			string newPostDesc = string.Empty;
			Guid currentPost = Guid.Parse(hdnCurrentPostId.Value);
			TextBox newPost = (TextBox)PageHelper.FindControlRecursive(this, "newPostText");
			newPostDesc = newPost.Text;
			Handler.AddPost(newPostDesc, RootPost.ParentCategory, currentPost);
			LoadPostList();
		}
	}
}